<template>
    <view class="diy-form-button dir-top-nowrap" :style="[boxStyle]">
        <view v-if="data.is_pay == 1" :style="{padding: `0 ${data.box_padding}rpx`}">
            <view class="dir-left-nowrap cross-center main-between">
                <view class="_diy-form-label"
                      :style="{color: data.title_color,padding:0}"
                      :class="{required: data.is_required}">
                    {{ data.title }}
                </view>

                <view class="update-btn box-grow-0" v-if="data.pay_update == 1 && data.pay_status === 'alone'"
                      @click="openUpdate">
                    <image :src="data.pay_update_icon"></image>
                </view>
            </view>

            <view class="b-box">
                <view v-if="data.pay_status === 'alone'" class="dir-top-nowrap">
                    <view class="dir-left-nowrap cross-center" stye="width:100%">
                        <view class="box-grow-1">
                            <view :class="data.pay_update == 0 ? 'box-grow-1': 'box-grow-0'"
                                  :style="{'color': data.label_color}"
                                  class="b-label t-omit-two">
                                {{ data.pay_title }}
                            </view>
                        </view>
                        <view :style="{'color': data.label_color}" class="b-price box-grow-0">
                            {{
                                FloatMul(pay_num * chen, pay_price || data.user_member_price) != 0 ? '￥' + FloatMul(pay_num * chen, pay_price || data.user_member_price) : '免费'
                            }}
                        </view>
                    </view>
                    <view class="dir-left-nowrap cross-center main-between"
                          style="margin-top: 20rpx"
                          v-if="data.has_stock == 1">
                        <view :style="{color: data.label_color}" class="yuan-num">数量
                            <template v-if="data.has_limit_stock_num == 0">
                                （仅剩{{ data.stock_num }}{{ data.goods_unit }}）
                            </template>
                        </view>
                        <view class="dir-left-nowrap cross-center">
                            <view
                                :style="{backgroundImage: `url(${pay_num == 1 ? '': ''})`}"
                                class="yuan-icon"
                                @click="changeLess"></view>
                            <view class="yuan-input">
                                <input
                                    v-model="pay_num"
                                    style="color: #242424;font-size: 24rpx;height: 100%;width:100%;text-align: center"
                                    type="number"
                                    @input="changeInput">
                            </view>
                            <view
                                :style="{backgroundImage: `url(${pay_num < maxStock || has_limit_max_stock == 1 ? '': ''})`}"
                                class="yuan-icon"
                                @click="changeAdd"
                            ></view>
                        </view>
                    </view>
                </view>
                <view v-if="data.pay_status === 'much'" style="width: 100%">
                    <view v-for="(item,index) in data.pay_price_list" :key="index" class="btn-much dir-top-nowrap">
                        <view class="dir-left-nowrap cross-center">
                            <view
                                :style="{'background-color': pay_select_index === index ? data.select_bg : data.noselect_bg, 'border-color': pay_select_index === index ? data.select_bg : data.noselect_bg}"
                                class="yuan box-grow-0" :class="{active: pay_select_index === index}"
                                @click="choosePay(item,index)"></view>
                            <view class="box-grow-1">
                                <view :style="{'color': data.label_color}" @click="choosePay(item,index)"
                                      class="b-label t-omit-two box-grow-1">
                                    {{ item.title }}
                                </view>
                            </view>
                            <view :style="{'color': data.label_color}" class="b-price box-grow-0">
                                {{
                                    FloatMul(pay_select_index === index ? pay_num * chen : 1, item.user_member_price) != 0 ? '￥' + FloatMul(pay_select_index === index ? pay_num * chen : 1, item.user_member_price) : '免费'
                                }}
                            </view>
                        </view>
                        <view v-if="pay_select_index === index && data.has_stock == 1"
                              style="margin-top: 20rpx"
                              class="dir-left-nowrap cross-center main-between">
                            <view :style="{color: data.label_color}" class="yuan-num" style="margin-left:52rpx">数量
                                <template v-if="data.has_limit_stock_num == 0">
                                    （仅剩{{ item.stock_num }}{{ data.goods_unit }}）
                                </template>
                            </view>
                            <view class="dir-left-nowrap cross-center">
                                <view
                                    :style="{backgroundImage: `url(${pay_num == 1 ? '': ''})`}"
                                    class="yuan-icon"
                                    @click="changeLess"></view>
                                <view class="yuan-input">
                                    <input
                                        v-model="pay_num"
                                        style="color: #242424;font-size: 24rpx;height: 100%;width:100%;text-align: center"
                                        type="number"
                                        @input="changeInput">
                                </view>

                                <view
                                    :style="{backgroundImage: `url(${pay_num < maxStock || has_limit_max_stock == 1 ? '': ''})`}"
                                    class="yuan-icon"
                                    @click="changeAdd"
                                ></view>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
        </view>
        <view :style="[btnStyle,{background: '#cccccc',color: 'white', borderColor: '#cccccc'}]"
              v-if="data.time_status == 1 && new Date((data.time_at || '').replace(/-/g, '/')).getTime() < new Date().getTime()"
              class="main-center cross-center">
            活动已结束
        </view>
        <view v-else :style="[btnStyle]" class="main-center cross-center" @click="validSubmit">
            {{ data.btn_title }}
        </view>
        <app-model v-if="updateModel" v-model="updateModel" type="2">
            <template slot="header">
                <view class="model-label" @click.stop="stopClick">修改价格</view>
            </template>
            <template slot="content">
                <view style="width: 393rpx;border-bottom: 1px solid #BEC3C7;margin: 0 auto"
                      class="dir-left-nowrap cross-center" @click.stop="stopClick">
                    <view style="font-size: 46rpx;font-weight: bold;color: #FF4544;">￥</view>
                    <app-input v-model="temp_pay_price" style="padding-right: 24rpx"
                               type="digit"
                               :input-style="{fontSize: '46rpx',fontWeight:'bold'}"
                               placeholder-style="font-size:30rpx;color:#BEC3C7"
                               placeholder="请输入修改后价格"
                    ></app-input>
                </view>
                <view class="dir-left-nowrap cross-center main-center" style="margin:35rpx 0">
                    <view class="main-center cross-center model-update-cancel-btn" @click="updateModel = false">
                        取消
                    </view>
                    <view style="width: 40rpx"></view>
                    <view class="main-center cross-center model-update-submit-btn" @click="submitUpdate">确定</view>
                </view>
            </template>
        </app-model>
        <app-model v-model="limitModel" type="2">
            <template slot="header">
                <view class="model-label" @click.stop="stopClick">提交</view>
            </template>
            <template slot="content">
                <view class="dir-top-nowrap cross-center" @click.stop="stopClick">
                    <view style="font-size: 30rpx;color: #242424;">{{ limitText }}</view>
                    <view class="main-center cross-center model-limit-btn" @click="limitModel = false">
                        确定
                    </view>
                </view>
            </template>
        </app-model>
        <app-model v-model="secondModel" type="2">
            <template slot="header">
                <view class="model-label" @click.stop="stopClick">提交</view>
            </template>
            <template slot="content">
                <view class="dir-top-nowrap cross-center" @click.stop="stopClick">
                    <view style="font-size: 30rpx;color: #242424;">{{ data.before_text }}</view>
                    <view class="dir-left-nowrap cross-center main-center" style="margin-top: 35rpx">
                        <view class="main-center cross-center model-update-cancel-btn" @click="secondModel = false">
                            取消
                        </view>
                        <view style="width: 40rpx"></view>
                        <view class="main-center cross-center model-update-submit-btn" @click="afterSubmit">确定</view>
                    </view>
                </view>
            </template>
        </app-model>
    </view>
</template>

<script>
import appModel from '../../basic-component/app-model/app-model.vue';
import formValue from './formValue.js';

export default {
    name: 'diy-form-button',
    props: {
        value: {
            type: Object
        },
        error: String,
        template_message_list: Array,
        otherForm: Array,
        formId: [Number, String],
        pageId: [Number, String],
    },
    components: {appModel},

    data() {
        return {
            secondModel: false,
            limitModel: false,
            limitText: null,
            updateModel: false,
            clickSubmit: false,

            tempOtherForm: this.otherForm,

            pay_select_index: 0,

            temp_pay_price: '',
            pay_price: '',
            data: {},
            chen: 1,
            pay_num: 1,

            has_limit_max_stock: 0,
            maxStock: 0,
        }
    },

    computed: {
        btnStyle() {
            let {
                btn_height,
                btn_radius,
                btn_color,
                btn_bg,
                btn_border_color,
                btn_padding,
            } = this.data;
            return {
                height: `${btn_height}rpx`,
                background: btn_bg,
                margin: `0 ${btn_padding}rpx`,
                color: btn_color,
                borderWidth: '1px',
                borderStyle: 'solid',
                borderColor: btn_border_color,
                borderRadius: `${btn_radius}rpx`,
            }
        },
        boxStyle() {
            let {
                bg_color,
            } = this.data;
            return {
                backgroundColor: bg_color,
                padding: `20rpx 0`,
            }
        },
    },
    created() {
        this.data = this.value;
        let {pay_status, has_limit_stock_num, pay_price_list, stock_num} = this.data;
        this.has_limit_max_stock = has_limit_stock_num

        if (pay_status === 'much') {
            this.maxStock = pay_price_list[this.pay_select_index].stock_num
        } else {
            this.maxStock = stock_num;
        }
    },
    watch: {
        otherForm: {
            handler(newVal) {
                this.tempOtherForm = newVal || [];
                let {has_calendar, calendar_key} = this.data;
                if (has_calendar == 1) {
                    let chen = 1;
                    for (let i = 0; i < this.tempOtherForm.length; i++) {
                        let {key, value} = this.tempOtherForm[i];
                        if (
                            key === 'calendar'
                            && value
                            && value.s.key === calendar_key
                            && value.after
                            && value.before
                            && value.s.is_alone == 0
                        ) {
                            chen = value.s.has_kuatian == 0 ? value.data.length : value.data.length - 1;
                            break;
                        }
                    }
                    this.chen = chen;
                }
                console.warn('表单数据刷新=>', this.tempOtherForm);
            },
            immediate: true,
            deep: true
        },
    },
    methods: {
        FloatMul(arg1, arg2) {
            if(!arg1 || !arg2){
                return 0;
            }
            var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
            try {
                m += s1.split(".")[1].length
            } catch (e) {
            }
            try {
                m += s2.split(".")[1].length
            } catch (e) {
            }
            let number =Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
            return Number(number.toString().match(/^\d+(?:\.\d{0,2})?/))
        },

        toExchange() {
            let {goods} = this.data;
            let mch_list = [{
                form_list_id: this.formId,
                page_id: this.pageId,
                mch_id: 0,
                goods_list: [{
                    id: goods.id,
                    attr: goods.attrs,
                    num: 1,
                    cat_id: 0,
                    goods_attr_id: goods.attr_id,
                }]
            }];
            let url = `/pages/order-submit/order-submit?mch_list=${JSON.stringify(mch_list)}`;
            url += `&preview_url=${encodeURIComponent(this.$api.diy.order_preview)}&submit_url=${encodeURIComponent(this.$api.diy.order_submit)}&plugin=diy`;
            uni.navigateTo({
                url: url
            })
        },
        changeInput(event) {
            this.$nextTick(() => {
                if (event.target.value < 1) {
                    this.pay_num = 1;
                } else if (event.target.value > this.maxStock && this.has_limit_max_stock == 0) {
                    this.pay_num = this.maxStock || 1;
                    uni.showToast({title: '库存不足', icon: 'none'});
                }
            })
        },
        changeLess() {
            this.pay_num = this.pay_num > 1 ? --this.pay_num : 1;
        },
        changeAdd() {
            if (this.pay_num >= this.maxStock && this.has_limit_max_stock == 0) {
                this.pay_num = this.maxStock || 1;
                uni.showToast({title: '库存不足', icon: 'none'});
            } else {
                this.pay_num = ++this.pay_num;
            }
        },
        choosePay(item, index) {
            this.maxStock = item.stock_num;
            this.pay_num = 1;
            this.pay_select_index = index;
        },
        validSubmit() {
            if (this.error) {
                uni.showToast({title: this.error, icon: 'none'});
                return false;
            }
            if (this.data.before_status == 1) {
                this.secondModel = true;
            } else {
                this.afterSubmit();
            }
        },
        afterSubmit() {
            if(this.clickSubmit) {
                return false;
            }
            this.clickSubmit = true;
            this.$subscribe(this.template_message_list).then(res => {
                this.handleSubmit();
            }).catch(() => {
                this.handleSubmit();
            });
        },
        handleSubmit() {
            uni.showLoading({
                mask: true
            });
            this.secondModel = false;
            let form_data = [].concat(this.tempOtherForm, new formValue({
                key: 'button',
                label: this.data.title,
                value: this.getValue(),
                required: 0
            }).getObject());
            let para = {
                form_list_id: this.formId,
                page_id: this.pageId,
                form_data: JSON.stringify(form_data),
            }
            if(this.data.is_pay == 1) {
                para.new_price = this.pay_price || 0;
                if(this.data.pay_status === 'much') {
                    para.new_index = this.pay_select_index
                }
            }
            this.$request({
                url: this.$api.diy.new_form,
                data: para,
                method: 'POST',
            }).then(response => {
                uni.hideLoading();
                this.clickSubmit = false;
                if (response.code === 0) {
                    if(response.data.is_pay == 1) {
                        this.toExchange();
                    } else {
                        this.$emit('click', true);
                        uni.navigateTo({
                            url: '/plugins/diy/form-success?form_id=' + response.data.form_id
                        })
                    }
                    return;
                    if (response.data.id) {
                        this.onPay(response.data.id, response.data.form_id);
                    } else {
                        this.$emit('click', true);
                        uni.navigateTo({
                            url: '/plugins/diy/form-success?form_id=' + response.data.form_id
                        })
                    }
                } else {
                    this.limitText = response.msg;
                    this.limitModel = true;
                }
            }).catch(response => {
                this.clickSubmit = false;
                uni.hideLoading();
            });

        },
        onPay(pay_id,form_id){
            const self = this;
            self.$payment.pay(pay_id).then(e => {
                this.$emit('click',true);
                uni.navigateTo({
                    url: '/plugins/diy/form-success?form_id=' + form_id
                })
            }).catch(e => {
                console.log(pay_id)
                self.cancel(pay_id);
            });
        },
        cancel(pay_id) {
            uni.showLoading({
                mask: true
            });
            this.$request({
                url: this.$api.diy.cancel,
                data: {
                    pay_id: pay_id
                },
                method: 'post'
            }).then(response=>{
                uni.hideLoading();
                if(response.code === 0) {
                    uni.navigateTo({
                        url: '/plugins/diy/form-success?is_error=1'
                    })
                }else {
                    uni.showToast({
                        title: response.msg,
                        icon: 'none',
                        duration: 1000
                    });
                }
            }).catch(() => {
                uni.hideLoading();
            });
        },
        getValue() {
            let {
                pay_status,
            } = this.data,title;

            let pay_price, attr_key;
            if (pay_status === 'alone') {
                pay_price = this.pay_price || this.data.pay_price;
                attr_key = '';
                title = this.data.pay_title;
            } else {
                let item = this.data.pay_price_list[this.pay_select_index];
                if (!item) {
                    uni.showToast({title: '请选择', icon: 'none'});
                    return;
                }
                title = item.title;
                pay_price = item.pay_price;
                attr_key = item.key;
            }
            let value = {};
            value.title = title;
            value.pay_price = pay_price;
            value.attr_key = attr_key;
            value.num = this.pay_num;
            value.is_pay = this.data.is_pay
            value.after_send_status = this.data.after_send_status
            value.after_send = {
                after_send_plugin: this.data.after_send_plugin,
                after_send_lottery_limit: this.data.after_send_lottery_limit,
                after_send_price: this.data.after_send_price,
                after_send_integral: this.data.after_send_integral,
                after_send_member_name: this.data.after_send_member_name,
                after_send_coupon: this.data.after_send_coupon,
                after_send_card: this.data.after_send_card
            }
            return value;
        },

        stopClick() {},
        openUpdate() {
            this.temp_pay_price = this.pay_price || this.data.pay_price;
            this.updateModel = true;
        },
        money(val) {
            let num = val.toString(); //先转换成字符串类型
            if (num.indexOf('.') == 0) { //第一位就是 .
                num = '0' + num
            }
            num = num.replace(/[^\d.]/g, "");  //清除“数字”和“.”以外的字符
            num = num.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
            num = num.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
            num = num.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
            if (num.indexOf(".") < 0 && num != "") {
                num = parseFloat(num);
            }
            return +num
        },
        submitUpdate() {
            if(this.temp_pay_price > 0) {
                if (this.temp_pay_price > 9999999) {
                    this.pay_price = 9999999;
                } else {
                    this.pay_price = this.money(this.temp_pay_price);
                }
            }else {
                uni.showToast({title: '价格需大于0', icon: 'none'});
            }
        },
    }
}
</script>

<style scoped lang="scss">
._diy-form-label {
    padding-left: #{20rpx};
    font-size: #{30rpx};
    white-space: nowrap;
    margin-bottom: #{18rpx};
}

._diy-form-label.required:after {
    content: '*';
    margin-left: 6#{rpx};
    color: #FF4544;
}

.diy-form-button {
    .model-label {
        font-size: 32#{rpx};
        color: #242424;
        text-align: center;
        padding: 40#{rpx} 0;
    }

    .yuan {
        height: 32#{rpx};
        width: 32#{rpx};
        border-radius: 50%;
        margin-right: 20#{rpx};
        border: 1px solid #E5E7EC;
    }

    .yuan-input {
        width: 80#{rpx};
        height: 48#{rpx};
        margin: 0 6#{rpx};
        background: #F7F7F7;
        border-right: 8#{rpx};
        font-size: 24#{rpx};
        color: #242424;
    }

    .yuan-icon {
        background-size: 100% 100%;
        background-repeat: no-repeat;
        width: 48#{rpx};
        height: 48#{rpx};
        border-radius: 8#{rpx};
    }

    .yuan-num {
        font-size: 24#{rpx};
    }

    .yuan.active {
        border-color: #ff4544;
        background: #ff4544;
        position: relative;
    }

    .yuan.active:after {
        box-sizing: content-box;
        content: "";
        border: 1px solid white;
        border-left: 0;
        border-top: 0;
        height: 14#{rpx};
        left: 10#{rpx};
        position: absolute;
        top: 4#{rpx};
        transform: rotate(45deg);
        width: 6#{rpx};
        transition: transform .15s ease-in .05s;
        transform-origin: center;
    }

    .model-update-cancel-btn {
        width: 200#{rpx};
        height: 80#{rpx};
        color: #FF4544;
        background: white;
        border-radius: 40#{rpx};
        border: 1px solid #ff4544
    }

    .model-update-submit-btn {
        width: 200#{rpx};
        height: 80#{rpx};
        color: #FFFFFF;
        background: #ff4544;
        border-radius: 40#{rpx}
    }

    .model-limit-btn {
        border-radius: 40#{rpx};
        font-size: 30#{rpx};
        color: #FFFFFF;
        margin-top: 50#{rpx};
        width: 400#{rpx};
        height: 80#{rpx};
        background: #FF4544;
    }

    .btn-much {
        margin-top: 38#{rpx};
    }

    .btn-much:first-child {
        margin-top: 0;
    }

    .b-box {
        margin-top: 18#{rpx};
        margin-bottom: 56#{rpx};
    }

    .b-price {
        font-size: 30#{rpx};
        font-weight: bold;
        word-break: break-all;
        color: #242424;
    }

    .b-label {
        margin-right: 10#{rpx};
        font-size: 30#{rpx};
        color: #242424;
        max-width: 400#{rpx};
    }

    .update-btn {
        height: 40#{rpx};
        width: 40#{rpx};
        margin-bottom: #{18rpx};

        > image {
            height: 100%;
            width: 100%;
            display: block;
        }
    }
}
</style>
